package com.heima.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
  if (StringUtils.isBlank(dto.getPhone())&& StringUtils.isBlank(dto.getPassword())){
        String token = AppJwtUtil.getToken(0L);
        HashMap map = new HashMap();
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
    //ApUser user = apUserMapper.selectByPhone(dto.getPhone());
        ApUser user = this.lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
        if (BeanUtil.isEmpty(user)){
        throw  new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
    }
    String password = dto.getPassword();
    boolean right = BCrypt.checkpw(password, user.getPassword());
    if (!right){
        throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
    if (user.getStatus()){
        throw  new CustomException(AppHttpCodeEnum.INVALID_STATUS);
    }

    String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
    HashMap map = new HashMap();
    map.put("user",user );
    map.put("token",token);
    return ResponseResult.okResult(map);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
